package com.tzjw.marketweixin.components;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 数据库连接测试组件
 *
 * @author hayden
 * @since 2023/09/06 10:09
 */
@Component
public class DBTester {
    private Connection connection = null;
    @Value("${spring.datasource.driver-class-name}")
    private String driver;
    @Value("${spring.datasource.url}")
    private String url;
    @Value("${spring.datasource.username}")
    private String username;
    @Value("${spring.datasource.password}")
    private String password;

    @PostConstruct
    public void init() {
        doTest(driver, url, username, password);
    }

    /**
     * 测试数据库连接
     * 场景说明：
     * 防止未开启数据库服务，启动web服务器接口请求执行引起的服务器内部错误
     */

    private void doTest(String driver, String dbUrl, String dbUsername, String dbPwd) {
        try {
            Class.forName(driver);
            connection = DriverManager.getConnection(dbUrl, dbUsername, dbPwd);
            System.out.println("==================================================");
            System.out.println("==========Database connection successful==========");
            System.out.println("==================================================");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("数据库驱动类型未找到");
        } catch (SQLException e) {
            throw new RuntimeException("数据库连接失败，应用程序停止。请检查连接配置");
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}


